<!DOCTYPE html>
<body>
<script>
class MyControl1 extends HTMLElement {
  static get formAssociated() { return true; }
  constructor() {
    super();
    this.internals_ = this.attachInternals();
    this.value_ = 'initial';
  }
  get value() {
    return this.value_;
  }
  set value(v) {
    this.value_ = v;
    this.internals_.setFormValue(v);
  }
  formStateRestoreCallback(v, mode) {
    this.value = v;
    this.lastRestoreMode = mode;
  }
}
customElements.define('my-control-1', MyControl1);
</script>
<input id=emptyOnFirstVisit name="state">

<form action="../../resources/back.html" id="form1">
<my-control-1></my-control-1>
<my-control-1 id="nested-focus"><my-control-1 id="focus" tabindex=0></my-control-1></my-control-1>
<my-control-1 id="disabled" disabled></my-control-1>
<my-control-1 id="readonly" readonly></my-control-1>
<fieldset disabled><my-control-1 id="fieldset-disabled"></my-control-1></fieldset>
<my-control-2></my-control-2>
</form>

<script>

let $ = document.querySelector.bind(document);

function upgradeMyControl2() {
  class MyControl2 extends HTMLElement {
    static get formAssociated() { return true; }
    constructor() {
      super();
      this.internals_ = this.attachInternals();
      this.value_ = 'initial';
    }
    get value() {
      return this.value_;
    }
    set value(v) {
      this.value_ = v;
      this.internals_.setFormValue(v);
    }
    formStateRestoreCallback(v, mode) {
      this.value = v;
      this.lastRestoreMode = mode;
    }
  }
  customElements.define('my-control-2', MyControl2);
  customElements.upgrade($('my-control-2'));
}

function runTest() {
  let state = $('#emptyOnFirstVisit');
  if (!state.value) {
    // First visit
    state.value = 'visited';
    upgradeMyControl2();

    $('my-control-1').value = 'edit1';
    $('#focus').value = 'edit3';
    $('#nested-focus').value = 'edit4';
    $('#disabled').value = 'edit5';
    $('#readonly').value = 'edit6';
    $('#fieldset-disabled').value = 'edit7';
    $('my-control-2').value = 'edit2';
    setTimeout(() => { $('form').submit(); }, 100);
  } else {
    // Second visit
    upgradeMyControl2();
    parent.doneTest();
  }
}

$('#focus').focus();
window.onload = () => {
  setTimeout(runTest, 1);
};
</script>
</body>
